class Ruiqu::ProductsController < Ruiqu::BaseController
  before_action :set_store
  before_action :set_product, only: [:show, :edit, :update, :unuse, :remove_image, :unshow]
  def new
    @product = StoreProduct.new
  end

  def create
    @product = @store.products.new(store_product_params.except(:images_attributes))
    if @product.save
      status = ImageService.call(store_product_params[:images_attributes], @product)
      if !status.success?
        @product.delete
        redirect_to new_ruiqu_store_product_path, notice: status.notice
      else
        redirect_to ruiqu_store_products_path
      end
    else
      redirect_to new_ruiqu_store_product_path, notice: @product.errors.full_messages.first
    end
  end

  def index
    @store_products = @store.products.uncustoms.useable
  end

  def unuse
    @product.unuse!
    redirect_to ruiqu_store_products_path
  end

  def edit

  end

  def unshow

  end

  def remove_image
    images = @product.images.by_ids(params[:image_ids])
    images.delete_all
    render json: {status: true, msg: "已经删除存在的照片"}
  end

  def update
    status = ImageService.call(store_product_params[:images_attributes], @product, type: 'update')
    if status.success?
      @product.update!(store_product_params.except(:images_attributes))
    end
    redirect_to ruiqu_store_products_path
  end

  def show

  end

  private
  def set_store
    @store ||= current_store
  end

  def store_product_params
    params.require(:store_product).permit(
                                      :name,
                                      :price,
                                      :vip_price,
                                      :vipable,
                                      :showable,
                                      :useable,
                                      :introduce,
                                      :format,
                                      :store_product_category_id,
                                      images_attributes: [
                                        :image
                                      ]
                                    )
  end

  def set_product
    @product = StoreProduct.find(params[:id])
  end
end
